import { defineStore } from 'pinia'
import type { UserInfoParam } from "@/api/user"
import {saveUserInfo, wxLogin} from "@/api/user";
import {getCollectList, postDeleteCollect, postInsertCollect} from "@/api/collect";
import type {User} from "@/api/book";
import type {Collect} from "@/api/collect";
interface LoginRes {
  errMsg: string
  code: string
}
interface UserState {
  id: string
  token: string
  userInfo: User | null
  collectList: Collect[]
}
export default defineStore('user', {
  state(): UserState{
    return {
      id: 'user',
      token: '',
      userInfo: null,
      collectList: []
    }
  },
  actions: {
    setToken(token: string) {
      this.token = token
      uni.setStorageSync('token',token)
    },
    async weixinLogin() {
      try {
        const data = await new Promise<LoginRes>((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success(res){
              resolve(res as LoginRes)
            },
            fail(res){
              console.warn("微信登录失败", res)
              reject(res as LoginRes)
            }
          })
        })
        if(data?.errMsg === 'login:ok'){
          const response = await wxLogin({ code: data.code },{appid: 'wxf810c25077850c1e'})
          // 判断是否有用户名，如果没有则表明用户是首次登录
          if(response.code === 200){
            this.userInfo = response.data
            this.token = response.token || ''
            await this.storeCollectList()
            return Promise.resolve(this.userInfo)
          }
        }else{
          return Promise.reject('登录失败')
        }
      }catch (e) {
        console.warn("微信登录异常", e)
        return Promise.reject(e)
      }
    },
    async weixinInfo(){
      try {
        const userInfo = await new Promise<UniNamespace.UserInfo>((resolve, reject) => {
          uni.getUserProfile({
            desc: '用于展示个人头像和昵称',
            lang: 'zh_CN',
            success(res){
              resolve(res.userInfo)
            },
            fail(res){
              console.log('获取用户详细信息失败了', res)
              reject(res)
            }
          })
        })
        if(userInfo) {
          const param: UserInfoParam = {
            headUrl: userInfo.avatarUrl,
            name: userInfo.nickName
          }
          const { code, data, msg } = await saveUserInfo(this.userInfo!.uId, param)
          if(code === 200){
            this.userInfo = data
            await this.storeCollectList()
          }
        }
      }catch (e) {
        console.warn(e)
      }
    },
    async storeCollectList(){
      if(this.userInfo?.uId){
        const collectList = await getCollectList(this.userInfo?.uId)
        this.collectList = collectList.data
      }
    },
    async collectBook(bId: number){
      if(this.userInfo?.uId){
        const data = await postInsertCollect({uid: this.userInfo.uId, bid: bId})
        if(data){
          this.collectList.push(data.data)
          return Promise.resolve(data)
        }else{
          return Promise.reject()
        }
      }
    },
    async unCollectBook(bId: number){
      if(this.userInfo?.uId){
        const data = await postDeleteCollect({uId: this.userInfo.uId, bids: bId.toString()})
        if(data){
          await this.storeCollectList()
          return Promise.resolve(data)
        }else{
          return Promise.reject()
        }
      }
    },
    saveUserInfo(userInfo: User){
      this.userInfo = userInfo
    }
  },
  persist: {
    enabled: true,
  },
})